package com.dk.springmvc02.controller;

import com.dk.springmvc02.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UserController {
    @RequestMapping(
            //可以设置多个请求映射，可以使用路径请求参数需要配置使用@PathVariable注解
            value = {"/","/index/{userId}"},
            method = RequestMethod.GET,
            //只接受请求行中携带username和password参数的请求
            params = {"username","password"},
            //只接受请求头中携带Content-Type=text/html;charset=UTF-8的请求
            headers = {"Content-Type=text/html;charset=UTF-8"}
    )
    public String index(@RequestParam("username") String name, String password, @PathVariable int userId) {
        System.out.println(name);
        System.out.println(password);
        System.out.println(userId);
        return "index";
    }

    /**
     * 获取请求参数使用传统servletAPI方式
     */
    @GetMapping("/getParamByServletAPI")
    public String getParamByServletAPI(HttpServletRequest request){
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");
        System.out.println("username = " + username);
        System.out.println("pwd = " + pwd);
        return "index";
    }

    /**
     * 获取请求参数根据方法形参，适用于字面量参数spring会自动映射
     */
    @GetMapping("/getParamByMethodArgs")
    public String getParamByMethodArgs(String name,int age){
        System.out.println("name = " + name);
        System.out.println("age = " + age);
        return "index";
    }

    /**
     * 根据@RequestParam注解获取参数，将处理器的形参和请求参数设置映射关系
     */
    @GetMapping("/getParamByRequestParam")
    public String getParamByRequestParam(@RequestParam("username") String name,@RequestParam("password") String pwd){
        System.out.println("name = " + name);
        System.out.println("pwd = " + pwd);
        return "index";
    }

    /**
     * 使用命令对象方式获取参数，spring会将请求参数和实体类参数进行映射
     */
    @GetMapping("/getParamByCommandObject")
    public String getParamByCommandObject(User user){
        System.out.println("user = " + user);
        return "index";
    }

    /**
     * 获取请求体中的参数
     */
    @PostMapping(value = "/getParamByRequestBody")
    @ResponseBody
    public User getParamByRequestBody(@RequestBody User user){
        System.out.println("user = " + user);
        return user;
    }

}
